package com.uduemc.biso.web.api.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.uduemc.biso.core.extities.center.SysServer;
import com.uduemc.biso.web.api.server.ServerService;
import com.uduemc.biso.web.utils.IpUtil;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/api/node/*", filterName = "ipFilter")
public class IpFilter extends OncePerRequestFilter {

	@Autowired
	private ServerService serverServiceImpl;

	private static final Logger logger = LoggerFactory.getLogger(IpFilter.class);

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		boolean bool = false;
		String ipAddr = IpUtil.getIpAddr(request);
		List<SysServer> findOkAll = serverServiceImpl.getAllowAccessIPServer();
		for (SysServer server : findOkAll) {
			if (server.getIpaddress().equals(ipAddr)) {
				bool = true;
				logger.info("allow access with ip address: " + ipAddr);
				break;
			} else {
				logger.info("ip not access, server ip address: " + server.getIpaddress() + " access ip: " + ipAddr);
			}
		}

		if ("0:0:0:0:0:0:0:1".equals(ipAddr)) {
			bool = true;
			logger.info("localhost ip address: " + ipAddr);
		}

		if (bool) {
			filterChain.doFilter(request, response);
		} else {
			logger.info("not allow access with ip address: " + ipAddr);
		}
	}

}
